package com.library.controller;

import com.library.bean.User;
import com.library.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController{

    @Resource
    private UserService us; // 注入 UserService 服务类的实例，用于处理业务逻辑

    @RequestMapping("/register")
    public String register(MultipartFile mf ,@Valid User user, BindingResult bindingResult, Model model) throws IOException {
        // 如果表单验证有错误
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors(); // 获取所有字段错误
            Map<String, String> map = new HashMap<>(); // 创建一个 Map 存储字段错误信息
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage()); // 将字段错误信息放入 Map 中
            }
            model.addAttribute("errors", map); // 将错误信息添加到模型中
            return "forward:/register.jsp"; // 转发到注册页面，显示错误信息
        }
        int result = us.userRegister(user); // 调用 UserService 的 userRegister 方法进行用户注册

        if (result == -1) {
            model.addAttribute("msg", "用户名已经存在"); // 如果用户名已存在，将错误信息添加到模型中
            return "forward:/register.jsp"; // 转发到注册页面，显示错误信息
        }
        System.out.println(mf);
        if(!mf.isEmpty() && mf !=null && mf.getContentType().contains("image")){
            String fileName=mf.getOriginalFilename();
            String o=System.currentTimeMillis()+fileName;
            String rrl="c:/images/"+o;
            String ool="/test2/images/"+o;
            System.out.println(rrl);
            mf.transferTo(new File(rrl));
            us.updateurl(ool,user.getUsername());
        }
        return "forward:/success.jsp"; // 注册成功，转发到成功页面
    }


    @RequestMapping("/login")
    public String login(User user, Model model, HttpSession session){
        Map<String, Object> map = us.userLogin(user);
        if(map.containsKey("loginUser")){
            session.setAttribute("loginUser",map.get("loginUser"));
            return "redirect:/book.jsp";
        }
        model.addAttribute("msg",map.get("msg"));
        return "forward:/login.jsp";
    }

}